package com.ldkj.panzh.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.artemis.sdk.ArtemisHttpUtil;
import com.hikvision.artemis.sdk.config.ArtemisConfig;
import com.ldkj.panzh.param.DoorSearchParam;
import com.ldkj.panzh.service.DoorAccessService;
import com.ldkj.panzh.utils.CommentUtils;
import com.ldkj.panzh.vo.DoorInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 门禁功能 实现类
 *
 * @author qiancheng
 * @date 2025-11-18
 */
@Slf4j
@Service
public class DoorAccessServiceImpl implements DoorAccessService {

    // API网关相关常量
    private static final String ARTEMIS_PATH = "/artemis";
    private static final String GET_DOOR_API = ARTEMIS_PATH + "/api/resource/v2/door/search";
    // 门禁状态查询接口
    private static final String GET_DOOR_STATUS_API = ARTEMIS_PATH + "/api/acs/v1/door/status";

    // 接口参数常量
    private static final String PAGE_NO = "pageNo";
    private static final String PAGE_SIZE = "pageSize";
    private static final String SUCCESS_CODE = "0";

    @Autowired
    public CommentUtils commentUtils;

    /**
     * 查询门禁点列表
     *
     * @param doorSearchParam 查询参数
     * @return 门禁状态数据
     */
    @Override
    public List<DoorInfoVo> queryDoorStates(DoorSearchParam doorSearchParam) {

        //设置平台参数（优先使用参数中的值，否则使用配置文件默认值）
        ArtemisConfig config = commentUtils.createArtemisConfig(
                doorSearchParam.getAppKey(),
                doorSearchParam.getAppSecret(),
                doorSearchParam.getHost());

        // 准备基础参数
        Map<String, String> baseParamMap = new HashMap<>(4);
        baseParamMap.put(PAGE_NO, String.valueOf(doorSearchParam.getPageNo()));
        baseParamMap.put(PAGE_SIZE, String.valueOf(doorSearchParam.getPageSize()));

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_DOOR_API);
        List<DoorInfoVo> resultList = new ArrayList<>();

        try {
            String body = JSON.toJSONString(baseParamMap);
            String response = ArtemisHttpUtil.doPostStringArtemis(
                    config, pathMap, body, null, null, "application/json");
            JSONObject jsonObject = JSON.parseObject(response);
            String code = jsonObject.getString("code");

            if (SUCCESS_CODE.equals(code)) {
                JSONObject data = jsonObject.getJSONObject("data");
                if (data != null) {
                    String list = data.getString("list");
                    if (list != null && !list.isEmpty()) {
                        resultList = JSON.parseArray(list, DoorInfoVo.class);
                        // 批量查询状态并填充
                        fillDoorStatus(config, resultList);
                    }
                }
            } else {
                String errorMsg = String.format("接口返回错误: %s，响应内容: %s",
                        jsonObject.getString("msg"), response);
                log.error(errorMsg);
                return null;
            }
        }catch (Exception e) {
            String errorMsg = String.format("解析门禁列表返回结果失败!");
            log.error(errorMsg, e);
        }
        return resultList;
    }

    /**
     * 批量查询并填充门禁状态
     *
     * status - 设备在线状态（0-离线，1-在线）
     * doorStatus - 门状态（0-关闭，1-开启，2-异常）
     * 
     * @param config Artemis配置
     * @param doorList 门禁列表
     */
    private void fillDoorStatus(ArtemisConfig config, List<DoorInfoVo> doorList) {
        if (doorList == null || doorList.isEmpty()) {
            return;
        }

        Map<String, String> pathMap = Collections.singletonMap("https://", GET_DOOR_STATUS_API);

        for (DoorInfoVo door : doorList) {
            try {
                // 准备状态查询参数
                Map<String, String> statusParam = new HashMap<>(2);
                statusParam.put("doorIndexCode", door.getIndexCode());

                String body = JSON.toJSONString(statusParam);
                String response = ArtemisHttpUtil.doPostStringArtemis(
                        config, pathMap, body, null, null, "application/json");

                JSONObject jsonObject = JSON.parseObject(response);
                String code = jsonObject.getString("code");

                if (SUCCESS_CODE.equals(code)) {
                    JSONObject data = jsonObject.getJSONObject("data");
                    if (data != null) {
                        // 设备在线状态：0-离线，1-在线
                        Integer onlineStatus = data.getInteger("onlineStatus");
                        door.setStatus(onlineStatus);

                        // 门状态：0-关闭，1-开启，2-异常
                        Integer doorStatus = data.getInteger("doorStatus");
                        door.setDoorStatus(doorStatus);

                        log.debug("门禁[{}]状态查询成功: 在线状态={}, 门状态={}", 
                                door.getName(), onlineStatus, doorStatus);
                    }
                } else {
                    log.warn("查询门禁[{}]状态失败: {}", door.getName(), jsonObject.getString("msg"));
                    // 状态查询失败时设置默认值
                    door.setStatus(0);
                    door.setDoorStatus(0);
                }
            } catch (Exception e) {
                log.error("查询门禁[{}]状态异常", door.getName(), e);
                // 异常时设置默认值
                door.setStatus(0);
                door.setDoorStatus(0);
            }
        }
    }

    /**
     * 查询门禁数量和状态统计
     *
     * @param doorSearchParam 查询参数
     * @return 统计数据（总数、在线数、离线数等）
     */
    @Override
    public Map<String, Object> queryDoorStats(DoorSearchParam doorSearchParam) throws Exception {
        // 查询所有门禁数据
        List<DoorInfoVo> allDoors = queryDoorStates(doorSearchParam);

        // 统计数据
        Map<String, Object> stats = new HashMap<>(8);
        int totalCount = allDoors.size();
        int onlineCount = 0;
        int offlineCount = 0;
        int openCount = 0;
        int closeCount = 0;
        int abnormalCount = 0;

        for (DoorInfoVo door : allDoors) {
            // 统计设备在线状态
            if (door.getStatus() != null) {
                if (door.getStatus() == 1) {
                    onlineCount++;
                } else {
                    offlineCount++;
                }
            }

            // 统计门禁开关状态
            if (door.getDoorStatus() != null) {
                switch (door.getDoorStatus()) {
                    case 0:
                        closeCount++;
                        break;
                    case 1:
                        openCount++;
                        break;
                    case 2:
                        abnormalCount++;
                        break;
                    default:
                        break;
                }
            }
        }

        stats.put("totalCount", totalCount);
        stats.put("onlineCount", onlineCount);
        stats.put("offlineCount", offlineCount);
        stats.put("openCount", openCount);
        stats.put("closeCount", closeCount);
        stats.put("abnormalCount", abnormalCount);
        stats.put("onlineRate", totalCount > 0 ? String.format("%.2f%%", (onlineCount * 100.0 / totalCount)) : "0.00%");

        return stats;
    }

    /**
     * 从host中提取IP地址（去除端口部分）
     * @param host 格式如 "183.222.26.212:1443"
     * @return 提取的IP地址，如 "183.222.26.212"
     */
    private String extractIpFromHost(String host) {
        if (host == null || host.isEmpty()) {
            throw new IllegalArgumentException("host参数不能为空");
        }
        // 分割host和端口（处理不带端口的情况）
        String[] parts = host.split(":", 2);
        return parts[0];
    }

}
